package com.cloud.wms.ui.print.activity;

import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.cloud.printer.Printer;
import com.cloud.widget.ScanText;
import com.cloud.wms.R;
import com.cloud.wms.app.FineExApplication;
import com.cloud.wms.base.BaseBarListActivity;
import com.cloud.wms.config.SpKey;
import com.cloud.wms.service.PrinterService;
import com.cloud.wms.ui.print.contact.SelectBoxContact;
import com.cloud.wms.ui.print.entity.PrinterBoxEntity;
import com.cloud.wms.ui.print.presenter.SelectBoxPresenter;
import com.cloud.wms.widget.dialog.AlertDialogBuilder;
import com.google.android.material.checkbox.MaterialCheckBox;
import com.inuker.bluetooth.library.BluetoothClient;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.cloud.wms.ui.print.activity.BluetoothPrinterActivity.REQUEST_BLUETOOTH;

/**
 * Created by FC on 2021/2/7.
 * Desc：
 */
public class SelectBoxActivity extends BaseBarListActivity<PrinterBoxEntity, SelectBoxPresenter> implements SelectBoxContact.View {
    @BindView(R.id.scan_text)
    ScanText scanText;
    @BindView(R.id.btn_print)
    TextView btnPrint;
    @BindView(R.id.tv_device_name)
    TextView tvDeviceName;
    @BindView(R.id.tv_change)
    TextView tvChange;
    @BindView(R.id.ll_print)
    LinearLayout llPrint;
    private BluetoothClient mClient;

    @Override
    protected String barTitle() {
        return "箱唛打印";
    }

    @Override
    protected int getResId() {
        return R.layout.activity_select_box_msg;
    }

    @Override
    protected int getItemResId() {
        return R.layout.item_select_box_msg;
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        initScanText(scanText);
        btnPrint.setEnabled(false);
        mClient = new BluetoothClient(this);
    }

    @Override
    protected void onScanHandle(String result, int resultCode) {
        super.onScanHandle(result, resultCode);
        scanText.addHistory(result);
        mPresenter.getBoxMsg(result);
    }

    @Override
    protected void onResume() {
        super.onResume();
        String name = FineExApplication.component().kv().getString(SpKey.PRINT_DEVICE_NAME, "");
        if (TextUtils.isEmpty(name)) {
            tvDeviceName.setText("请先绑定打印设备");
        } else {
            tvDeviceName.setText(name);
        }
    }

    @Override
    protected void bindItemData(BaseViewHolder helper, PrinterBoxEntity item) {
        helper.setText(R.id.tv_box_code, item.getBoxCode())
                .setText(R.id.tv_commodity_name, item.getCommodityName())
                .setText(R.id.tv_bar_code, item.getBarCode())
                .setText(R.id.tv_amount, item.getAmount() + "")
                .setText(R.id.tv_stock_type, "良品");
        ((MaterialCheckBox) helper.getView(R.id.cb_print)).setChecked(item.isSelect());
        ((MaterialCheckBox) helper.getView(R.id.cb_print)).setOnCheckedChangeListener((buttonView, isChecked) -> {
            mAdapter.getData().get(helper.getAdapterPosition()).setSelect(isChecked);
            for (int i = 0; i < mAdapter.getData().size(); i++) {
                PrinterBoxEntity entity = mAdapter.getData().get(i);
                if (entity.isSelect()) {
                    btnPrint.setEnabled(true);
                    return;
                }
            }
            btnPrint.setEnabled(false);
        });
    }

    @Override
    public void onSuccess(Message message) {
        switch (message.what) {
            case SelectBoxPresenter.GET_BOX_MSG_SUCCESS:
                List<PrinterBoxEntity> boxEntityList = (List<PrinterBoxEntity>) message.obj;
                if (boxEntityList.size() == 0) {
                    info("未查询到符合条件的数据");
                    return;
                }
                mAdapter.setNewInstance(boxEntityList);
                break;
        }
    }

    @Override
    protected void itemClickListener(BaseQuickAdapter<PrinterBoxEntity, BaseViewHolder> mAdapter, View view, int position) {
        super.itemClickListener(mAdapter, view, position);
//        for (int i = 0; i < mAdapter.getData().size(); i++) {
//            PrinterBoxEntity entity = mAdapter.getData().get(i);
//            if (i == position) {
//                entity.setSelect(!entity.isSelect());
//            } else {
//                entity.setSelect(false);
//            }
//        }
//        mAdapter.notifyDataSetChanged();
//        for (int i = 0; i < mAdapter.getData().size(); i++) {
//            PrinterBoxEntity entity = mAdapter.getData().get(i);
//            if (entity.isSelect()) {
//                btnPrint.setEnabled(true);
//                return;
//            }
//        }
//        btnPrint.setEnabled(false);
    }

    @OnClick({R.id.btn_print, R.id.tv_change})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_change:
                startActivity(new Intent(this, BluetoothPrinterActivity.class));
                break;
            case R.id.btn_print:
                if (!mClient.isBleSupported()) {
                    info("该设备不支持蓝牙");
                    return;
                }
                if (!mClient.isBluetoothOpened()) {
                    new AlertDialogBuilder(this)
                            .setTitle("开启蓝牙")
                            .setMessage("使用该功能需要开启蓝牙，请确认开启")
                            .setPositiveButton("去开启", (dialog, which) -> {
                                Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                                SelectBoxActivity.this.startActivityForResult(intent, REQUEST_BLUETOOTH);
                            })
                            .setNegativeButton("退出", (dialog, which) -> SelectBoxActivity.this.finish())
                            .show();
                    return;
                }
                if (TextUtils.isEmpty(FineExApplication.component().kv().getString(SpKey.PRINT_DEVICE_NAME, ""))) {
                    info("请先绑定打印设备");
                    return;
                }
                ArrayList<Printer> entities = new ArrayList<>();
                for (int i = 0; i < mAdapter.getData().size(); i++) {
                    PrinterBoxEntity entity = mAdapter.getData().get(i);
                    if (entity.isSelect()) {
                        entities.add(entity);
                    }
                }
                if (entities.isEmpty()) {
                    info("请选择箱唛后打印");
                    return;
                }
                PrinterService.startPrintService(this, entities);
                success("箱唛打印加入队列成功！");
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_BLUETOOTH && resultCode == RESULT_OK) {
            success("开启蓝牙成功");
        }
    }

    @Override
    protected void setupComponent() {
        getActivityComponent().inject(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }
}
